import { AsyncSubject } from 'rxjs'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { User } from '../../api'


@Injectable({ providedIn: 'root' })
export class LoginService {
  user: User | null
  ready$ = new AsyncSubject<void>()

  constructor (private http: HttpClient) {
    this.init()
  }

  async updateUser (): Promise<void> {
    if (!this.user) {
      return
    }
    // await this.http.put('http://192.168.3.54:9000/api/1/user', this.user).toPromise()
    await this.http.put('/api/1/user', this.user).toPromise()
  }

  private async init () {
    try {
      // {
      //     "id": 1,
      //     "username": "MayMrZ",
      //     "active_config": 1,
      //     "custom_connection_gateway": "ws://192.168.3.43:9000",
      //     "custom_connection_gateway_token": null,
      //     "config_sync_token": "a3ff091ef1e96f0f5842c1982a18d886d851fd2fa5ac3f04b5077eecb5281a12d9a81b313fd4d51903d5bb846e7c9a6465d37530465acef004f33a4dc68884d7",
      //     "is_pro": true,
      //     "is_sponsor": false,
      //     "github_username": "MayMrZ"
      // }
      // console.log('window.location.host: ', window.location.host)
      // this.user = (await this.http.get('/api/1/user').toPromise()) as User
      this.user = ({
        id: 1,
        active_config: 1,
        custom_connection_gateway: "ws://" + window.location.host.split(":")[0] + ":9000",
        custom_connection_gateway_token: null,
        config_sync_token: "a3ff091ef1e96f0f5842c1982a18d886d851fd2fa5ac3f04b5077eecb5281a12d9a81b313fd4d51903d5bb846e7c9a6465d37530465acef004f33a4dc68884d7",
        is_pro: true,
        is_sponsor: false,
        github_username: "MayMrZ"
      }) as User
    } catch {
      this.user = null
    }

    this.ready$.next()
    this.ready$.complete()
  }
}
